package net.yxsoft.kit;
import com.alibaba.druid.util.StringUtils;
import com.jcraft.jsch.*;

import java.io.*;

public class RemoteCommandKit {

    /**
     * 上传文件到远程主机远程
     * @param host  远程主机
     * @param port  端口（默认为22）
     * @param username  用户名
     * @param password  密码
     * @param localFilePath  本地服务器文件名称
     * @param localFilePath  本地服务器文件路径
     * @param remoteFilePath  远程文件路径
     * */
    public static String remoteFileUploader(String host,String port,String username,String password,String localFileName,String localFilePath,String remoteFilePath) throws Exception {
        //判断端口是否为null,否则默认为22
        if(StringUtils.isEmpty(port)){
            port="22";
        }
        JSch jsch = new JSch();
        try {
            // 创建 SSH 连接
            com.jcraft.jsch.Session session = jsch.getSession(username, host, Integer.parseInt(port));
            // 设置连接超时时间为1分钟
            session.setTimeout(1000*60*1);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            // 连接并进行身份验证
            session.connect();
            // 打开 SFTP 通道
            ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
            channel.connect();
            if(StringUtils.isEmpty(localFileName)){
                // 上传文件
                channel.put(localFilePath, remoteFilePath);
            }else{
                // 上传文件,使用自定义文件名
                channel.put(localFilePath, remoteFilePath+ "/" + localFileName);
            }
            // 关闭连接
            channel.disconnect();
            session.disconnect();

        } catch (Exception e) {
            throw e;
        }
        return null;
    }

    /**
     * 操作远程主键命令
     * @param host  远程主机
     * @param port  端口（默认为22）
     * @param username  用户名
     * @param password  密码
     * @param commands  执行命令
    * */
    public static String execRemoteCommand(String host,String port,String username,String password,String[] commands) throws Exception {
        //判断端口是否为null,否则默认为22
         if(StringUtils.isEmpty(port)){
             port="22";
         }
        JSch jsch = new JSch();
        try {
            // 创建 SSH 连接
            Session session = jsch.getSession(username, host, Integer.parseInt(port));
            // 设置连接超时时间为1分钟
            session.setTimeout(1000*60*1);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            // 连接并进行身份验证
            session.connect();
            // 打开远程命令执行通道
            ChannelExec channel = (ChannelExec) session.openChannel("exec");
            // 将多个命令用分号连接起来
            String command = String.join(";", commands);
            // 设置命令并执行
            channel.setCommand(command);
            channel.connect();
            channel.disconnect();
            session.disconnect();

        } catch (Exception e) {
            throw e;
        }
        return null;
    }


    /**
     * 操作远程主键命令(有返回)
     * @param host  远程主机
     * @param port  端口（默认为22）
     * @param username  用户名
     * @param password  密码
     * @param commands  执行命令
     * */
    public static int execRemoteCommandByResponse(String host,String port,String username,String password,String[] commands) throws Exception {
        //判断端口是否为null,否则默认为22
        if(StringUtils.isEmpty(port)){
            port="22";
        }
        JSch jsch = new JSch();
        try {
            // 创建 SSH 连接
            Session session = jsch.getSession(username, host, Integer.parseInt(port));
            // 设置连接超时时间为1分钟
            session.setTimeout(1000*60*1);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            // 连接并进行身份验证
            session.connect();
            // 打开远程命令执行通道
            ChannelExec channel = (ChannelExec) session.openChannel("exec");
            // 将多个命令用分号连接起来
            String command = String.join(";", commands);
            // 设置命令并执行
            channel.setCommand(command);
            channel.connect();

            StringBuilder output = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(channel.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                output.append(line).append(System.lineSeparator());
            }
            reader.close();
           // 获取命令执行的返回值
            int exitStatus = channel.getExitStatus();

            channel.disconnect();
            session.disconnect();
            return exitStatus;
        } catch (JSchException e) {
            e.printStackTrace();
            return -1;
        }
    }


    /**
     * 操作远程主键命令(有返回)
     * @param host  远程主机
     * @param port  端口（默认为22）
     * @param username  用户名
     * @param password  密码
     * @param commands  执行命令
     * */
    public static String  execRemoteCommandByReturn(String host,String port,String username,String password,String[] commands) throws Exception {
        //判断端口是否为null,否则默认为22
        if(StringUtils.isEmpty(port)){
            port="22";
        }
        JSch jsch = new JSch();
        try {
            // 创建 SSH 连接
            Session session = jsch.getSession(username, host, Integer.parseInt(port));
            // 设置连接超时时间为1分钟
            session.setTimeout(1000*60*1);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            // 连接并进行身份验证
            session.connect();
            // 打开远程命令执行通道
            ChannelExec channel = (ChannelExec) session.openChannel("exec");
            // 将多个命令用分号连接起来
            String command = String.join(";", commands);
            // 设置命令并执行
            channel.setCommand(command);
            channel.connect();

            StringBuilder output = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(channel.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                output.append(line).append(System.lineSeparator());
            }
            reader.close();
            // 获取命令执行的返回值
            int exitStatus = channel.getExitStatus();

            channel.disconnect();
            session.disconnect();
            return output.toString();
        } catch (JSchException e) {
            throw e;
        }
    }


    public static void main(String[] args) throws Exception {
        String host = "fl0613.vicp.net";
        int port = 22;
        String username = "root";
        String password = "Kudonet@123";
     /* String host = "112.2.36.10";
        int port = 1122;
        String username = "kudonet";
        String password = "Kudonet@1";
        String command = "ps aux|grep java";*/
//        上传文件到目标服务器
//        String remoteFilePath = "D:\\shuyu\\Desktop\\gjj_cron_jobSNAPSHOT.jar";
//        String remoteDirectory = "/home";
//        remoteFileUploader(host, "22", username, password, "sringtext",remoteFilePath,remoteDirectory);


                String appPath="/opt/chainmaker";
               String fileName="chainmaker-shuyu.tar.gz";
        //停止项目
        String[] stopCommands = {  "cd "+appPath+" && tar -xzvf "+fileName };
        execRemoteCommand(host, "1322", username, password, stopCommands);
        //远程主键连接
/*        String[] commands = {
                "cd /home",
                "nohup /usr/local/java/jdk1.8/bin/java -jar gjj_cron_jobSNAPSHOT1.jar &"
        };
        String returnline = execRemoteCommand(host, "22", username, password, commands);
        System.out.println(returnline);*/

/*        //查看服务节点状态
        String[] statusCommands = {
                "ps -ef | grep gjj_cron_jobSNAPSHOT1.jar | grep -v grep"
        };
        int response = execRemoteCommandByResponse(host, "22", username, password, statusCommands);
        System.out.println(response);*/
    }

}
